package com.so206.interceptr;


import com.so206.plugins.MyCacheManager;
import com.so206.po.SystemCcConfig;
import com.so206.service.SystemCcService;
import com.so206.utils.IpKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * CC防御拦截器
 */
@Component
public class WebFireWallInterceptor implements HandlerInterceptor {

    @Autowired
    private SystemCcService ccService;

    @Autowired
    private MyCacheManager myCacheManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SystemCcConfig config = myCacheManager.get("config");
        if (config == null) {
            config = ccService.getconfig(1L);
            myCacheManager.set("config", config, 60000);
        }
        String ip = IpKit.getRealIp(request);
        String uri = request.getRequestURI();
        Integer count = myCacheManager.get(ip);
        if (config.getStatus() == 1) {
            if (count == null) {
                myCacheManager.set(ip, 0, config.getTimeLong() * 1000);
            } else {
                if (count > config.getReqCount() | myCacheManager.get("method:" + ip) != null) {
                    myCacheManager.set(ip, ++count, 600000);
                    if (uri.contains("/kaptcha/")) {
                        return true;
                    }
                    if (uri.contains("/static/") | uri.contains("favicon.ico")) {
                        response.sendError(400);
                        myCacheManager.set("method:" + ip, request.getMethod(), 300000);
                        myCacheManager.set("url:" + ip, uri, 300000);
                        return false;
                    } else {
                        myCacheManager.set("method:" + ip, request.getMethod(), 300000);
                        myCacheManager.set("url:" + ip, uri, 300000);
                        request.getRequestDispatcher("/kaptcha/code?back=" + uri)
                                .forward(request, response);
                        return false;
                    }
                } else {
                    myCacheManager.set(ip, ++count, config.getTimeLong() * 1000);
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

}
